package com.changfen.client.zset;

import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

/**
 * @author 86180
 * @Classname SimpleRateLimiter
 * @Description TODO
 * @Date 2022/9/6 22:35
 */
public class SimpleRateLimiter {
    private StatefulRedisConnection<String, String> connection;

    public SimpleRateLimiter(StatefulRedisConnection<String, String> connection) {
        this.connection = connection;
    }

    public boolean isActionAllowed(String userId, String actionKey, int period , int maxCount) {
        String key = String.format("hist:%s:%s", userId, actionKey);

        long nowTs = System.currentTimeMillis();

        RedisCommands<String, String> sync = connection.sync();
        
        sync.zadd(key,nowTs,"" + nowTs);

        sync.zremrangebyscore(key,0,nowTs - period * 1000L);


        Long zcard = sync.zcard(key);

        sync.expire(key, period + 1);

        return zcard <= maxCount;

    }
}
